package com.sky.gateway.config;

import com.sky.gray.common.GrayRequestContextHolder;
import com.sky.gray.domain.GrayUser;
import com.sky.gray.service.IGrayService;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Objects;

public class GrayPublishFilter implements GlobalFilter, Ordered {

    private IGrayService grayService;

    public GrayPublishFilter(IGrayService grayService) {
        this.grayService = grayService;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        GrayRequestContextHolder.setGrayTag(false);

        // 从header中获取用户信息
        HttpHeaders headers = exchange.getRequest().getHeaders();
        String userId = Objects.requireNonNull(headers.get("USER_ID")).get(0);
        // 查询用户的灰度信息
        GrayUser user = GrayUser.builder().userId(userId).build();
        GrayUser grayUser = grayService.queryUserById(user);
        // Y:需要走灰度服务
        if ("Y".equalsIgnoreCase(grayUser.getGray())) {
            GrayRequestContextHolder.setGrayTag(true);

            ServerHttpRequest newRequest = exchange.getRequest().mutate()
                    .header("gray", GrayRequestContextHolder.getGrayTag().toString())
                    .build();
            ServerWebExchange newExchange = exchange.mutate()
                    .request(newRequest)
                    .build();
            return chain.filter(newExchange);
        }
        return chain.filter(exchange);

    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
